/*
' Copyright (c) 2012  DotNetNuke Corporation
'  All rights reserved.
' 
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
' DEALINGS IN THE SOFTWARE.
' 
*/

using System;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Security;
using System.Collections.Generic;
using DotNetNuke.Modules.DNNPagination.Components;
using System.Data;
using System.Web;
using System.Web.UI.WebControls;


namespace DotNetNuke.Modules.DNNPagination
{

    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The View class displays the content
    /// 
    /// Typically your view control would be used to display content or functionality in your module.
    /// 
    /// View may be the only control you have in your project depending on the complexity of your module
    /// 
    /// Because the control inherits from DNNPaginationModuleBase you have access to any custom properties
    /// defined there, as well as properties from DNN such as PortalId, ModuleId, TabId, UserId and many more.
    /// 
    /// </summary>
    /// -----------------------------------------------------------------------------
    public partial class View : DNNPaginationModuleBase, IActionable
    {
        public bool readFromPage = true;
        public int srcTabId = 94;
        public string modulePane = "ContentPane";
        public List<cContent> moduleText = new List<cContent>();
        public string separatorClass = "margin-top: 50px; border: solid 1px black;";
        public int PageIndex;

        #region Event Handlers

        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.Page_Load);
        }


        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// -----------------------------------------------------------------------------
        private void Page_Load(object sender, System.EventArgs e)
        {
            try
            {
                GridView1.ShowHeader = false;
                GridView1.ShowFooter = false;
                GridView1.BorderStyle = BorderStyle.None;

                if (DotNetNuke.Framework.AJAX.IsInstalled())
                {
                    DotNetNuke.Framework.AJAX.RegisterScriptManager();
                    if (!IsPostBack)
                    {
                        DataTable dt = new DataTable();
                        dt.Load(cObjectController.getObject(ModuleId));
                        if (dt.Rows.Count > 0)
                        {
                            PageIndex = 0;
                            Label1.Text = "0";
                            ShowData();
                        }
                        else
                        {
                            cObject o = new cObject();
                            o.moduleId = ModuleId;
                            o.srcTabId = -1;
                            o.srcPane = null;
                            o.TitleStyle = "";
                            o.ItemStyle = "";
                            o.SeparatorStyle = "";
                            o.ItemsPerPage = 10;

                            cObjectController.addObject(o);
                            Response.Redirect(Request.RawUrl);
                        }
                    }
                }
                
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        #endregion

        #region Optional Interfaces

        public ModuleActionCollection ModuleActions
        {
            get
            {
                ModuleActionCollection Actions = new ModuleActionCollection();
                Actions.Add(GetNextActionID(), Localization.GetString("EditModule", this.LocalResourceFile), "", "", "", EditUrl(), false, SecurityAccessLevel.Edit, true, false);
                return Actions;
            }
        }

        #endregion

        protected void ShowData()
        {
            if (readFromPage)
            {
                Dictionary<int, ModuleInfo> modules = new Dictionary<int, ModuleInfo>();
                ModuleController modCntr = new ModuleController();
                ModuleInfo mod = new ModuleInfo();

                modules = modCntr.GetTabModules(srcTabId);
                // Don't count deleted modules
                List<int> keysToDelete = new List<int>();
                foreach (KeyValuePair<int, ModuleInfo> pair in modules)
                {
                    if (pair.Value.IsDeleted)
                        keysToDelete.Add(pair.Key);
                }
                foreach (int k in keysToDelete)
                {
                    modules.Remove(k);
                }
                List<string> src = new List<string>();
                foreach (KeyValuePair<int, ModuleInfo> pair in modules)
                {
                    mod = pair.Value;
                    if (mod.PaneName == modulePane && mod.ModuleID != ModuleId)
                    {
                        DataTable dt = new DataTable();
                        dt.Load(cContentController.getHtmlText(mod.ModuleID));
                        cContent obj = new cContent();
                        obj.Text = HttpUtility.HtmlDecode(dt.Rows[0]["Content"].ToString());
                        obj.Text += "<div style=\"border-top: solid 1px black; width: 100%; \"></div>";
                        src.Add(obj.Text);                        
                        obj.Id = Convert.ToInt32(dt.Rows[0]["ItemID"].ToString());
                        moduleText.Add(obj);
                    }
                }

                PagedDataSource p = new PagedDataSource();
                p.DataSource = src;
                p.AllowPaging = true;
                p.PageSize = 2;
                p.CurrentPageIndex = PageIndex;

                Label1.Text = PageIndex.ToString();

                GridView1.DataSource = p;
                GridView1.DataBind();
            }
            else
            {

            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            e.Row.Attributes.Add("Style", "border: 0");
            foreach (TableCell cell in e.Row.Cells)
            {
                cell.Text = Server.HtmlDecode(cell.Text);
                cell.Attributes.Add("Style", "border: 0");
            }
        }

        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            PageIndex = Convert.ToInt32(Label1.Text) - 1;
            ShowData();
        }

        protected void LinkButton2_Click(object sender, EventArgs e)
        {
            PageIndex = Convert.ToInt32(Label1.Text) + 1;
            ShowData();
        }

    }

}
